<template>
  <BottomDrawer
    :visible="addVisible"
    :title="dataType.dataType === 0 ? '添加科室' : ' 编辑科室'"
    :width="500"
    @close="addVisible = false"
  >
    <div style="padding-bottom: 20px;">
      <el-row>
        <el-col :span="22" :offset="1">
          <PageForm
            ref="pageForm"
            :list="list"
            :form-data="formData"
            :rules="rules"
          >
          </PageForm>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button @click="addVisible = false">取消</el-button>
    </template>
  </BottomDrawer>
</template>

<script setup lang="ts">
import type { FormRules, ElTree } from 'element-plus';
import { addClinicDept, editClinicDept } from '@/api/clinic/index';
import stores from '@/store';
const userBaseStore = stores.useBaseDataStore();
const rules = reactive<FormRules<any>>({
  deptName: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
});
const defaultProps = {
  children: 'children',
  label: 'name',
};
// 获取序列列表
const permissionsId = ref([]);
const emits = defineEmits(['refresh']);
const pageForm = ref();
const dataType = defineProps<{ dataType: Number }>();
const superSwitch = ref(false);
const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

defineExpose<{
  open: () => void;
  open1: (data: any) => void;
}>({
  open: () => {
    addVisible.value = true;
    formData.value = {
      deptName: null,
      directorId: null,
    };
  },
  open1: (data: any) => {
    addVisible.value = true;
    formData.value = JSON.parse(JSON.stringify(data));
  },
});

const addVisible = ref(false);

const formData = ref<any>({
  deptName: null,
  directorId: '',
});

const list: any = computed(() => [
  {
    list: [
      {
        span: 24,
        label: '科室名',
        prop: 'deptName',
        component: 'input',
        labelWidth: '66',
        componentProps: {
          placeholder: '请输入科室名',
          width: '362px',
        },
      },
      {
        span: 24,
        label: '负责人',
        prop: 'directorId',
        component: 'select',
        labelWidth: '66',
        componentProps: {
          placeholder: '请输入负责人',
          width: '362',
        },
        get selectGroupOptions() {
          // const data = useEnum.getEnumSelect('actingStatusEnum');
          return userBaseStore.userSelectList.map((item: any) => ({
            label: item.empName,
            value: item.empId,
          }));
        },
      },
    ],
  },
]);
const handleCheck = () => {
  const checkedNodes = treeRef.value!.getCheckedNodes();
  //console.log(checkedNodes);

  // 直接使用Set来处理formData.value.permissions，确保唯一性
  const parentKeysSet: any = [];
  const parentId: any = [];
  // const parentIdSet: Set<any> = new Set();
  // 遍历勾选的节点
  checkedNodes.forEach((node: any) => {
    // 如果节点有父节点，并且父节点的key不在Set中，则添加到Set中
    if (node.parentId) {
      parentId.push(node.parentId);
      parentKeysSet.push(node.permissionsId);
    }
  });
};
const addDepApi = async () => {
  addClinicDept(formData.value)
    .then((res) => {
      if (res.code === '200') {
        ElMessage({
          type: 'success',
          message: '添加成功',
          duration: 2000,
        });
        emits('refresh');
        addVisible.value = false;
      } else {
        // ElMessage({
        //   type: 'error',
        //   message: res.msg || '添加失败',
        //   duration: 2000,

        // });
      }
    })
    .catch((error) => {
      //console.error('添加失败:', error);
    });
};
const editDepApi = async () => {
  editClinicDept(formData.value)
    .then((res) => {
      if (res.code === '200') {
        ElMessage({
          type: 'success',
          message: '编辑成功',
          duration: 2000,

        });
        emits('refresh');
        addVisible.value = false;
      } else {
        // ElMessage({
        //   type: 'error',
        //   message: res.msg || '添加失败',
        //   duration: 2000,

        // });
      }
    })
    .catch((error) => {
      //console.error('编辑失败:', error);
    });
};
const handleSubmit = async () => {
  const ruleFormRef = pageForm.value?.ruleFormRef;
  await ruleFormRef.validate((valid: any, fields: any) => {
    if (valid) {
      if (dataType.dataType === 0) {
        addDepApi();
      } else {
        editDepApi();
      }
    } else {
      //console.log('error submit!', fields);
    }
  });
};

const getRoleMenu = async () => {};
onMounted(() => {});
</script>
<style lang="scss" scoped>
.tree-box {
  border: 2px solid #e1e1e1;
  height: 300px;
  width: 451px;
  margin-top: 10px;
  overflow-y: auto;
}
</style>
